// 外发清单查询页面

let outsourceData = [];
let filteredData = [];

// 加载外发清单查询页面
function loadOutsourcePage(container) {
    container.innerHTML = `
        ${createPageTitle('外发清单查询', 'fas fa-truck')}
        ${createToolbar([
            '<button class="btn btn-primary" onclick="showAddOutsourceModal()">',
            '<i class="fas fa-plus mr-2"></i>新增外发',
            '</button>',
            '<button class="btn btn-secondary" onclick="loadOutsourceData()">',
            '<i class="fas fa-refresh mr-2"></i>刷新',
            '</button>',
            '<button class="btn btn-accent" onclick="exportOutsourceData()">',
            '<i class="fas fa-download mr-2"></i>导出',
            '</button>'
        ])}
        <div id="outsource-list">
            ${createOutsourceTable()}
        </div>
    `;
    
    // 绑定搜索事件
    const searchInput = document.getElementById('search-input');
    if (searchInput) {
        searchInput.addEventListener('input', debounce(handleOutsourceSearch, 300));
    }
    
    // 加载数据
    loadOutsourceData();
}

// 创建外发清单查询表格
function createOutsourceTable() {
    const headers = ['序号', '机型', '名称', '数量', '外发厂商', '外发日期', '预计返回日期', '实际返回日期', '状态', '备注', '位置'];
    
    return `
        <div class="table-container">
            <table class="table table-zebra w-full">
                <thead>
                    <tr>
                        ${headers.map(header => `<th>${header}</th>`).join('')}
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    ${filteredData.map(item => {
                        const statusClass = getOutsourceStatusClass(item.status);
                        
                        return `
                            <tr>
                                <td>${item.sequence || '-'}</td>
                                <td>${item.model || '-'}</td>
                                <td>${item.name || '-'}</td>
                                <td>${item.quantity || '-'}</td>
                                <td>${item.supplier || '-'}</td>
                                <td>${item.outsourceDate || '-'}</td>
                                <td>${item.expectedReturnDate || '-'}</td>
                                <td>${item.actualReturnDate || '-'}</td>
                                <td><span class="badge ${statusClass}">${item.status || '待外发'}</span></td>
                                <td>${item.remark || '-'}</td>
                                <td>${item.location || '-'}</td>
                                <td>
                                    <div class="btn-group">
                                        <button class="btn btn-sm btn-primary" onclick="editOutsource('${item.id}')">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        <button class="btn btn-sm btn-error" onclick="deleteOutsource('${item.id}')">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        `;
                    }).join('')}
                </tbody>
            </table>
        </div>
    `;
}

// 获取外发状态样式类
function getOutsourceStatusClass(status) {
    if (status === '已返回') return 'badge-success';
    if (status === '外发中') return 'badge-info';
    if (status === '待外发') return 'badge-ghost';
    if (status === '异常') return 'badge-error';
    return 'badge-ghost';
}

// 加载外发数据
async function loadOutsourceData() {
    try {
        const data = await outsourceAPI.getAll();
        outsourceData = data;
        filteredData = data;
        updateOutsourceTable();
    } catch (error) {
        showError('加载数据失败');
    }
}

// 更新外发表格
function updateOutsourceTable() {
    const tableContainer = document.getElementById('outsource-list');
    if (tableContainer) {
        tableContainer.innerHTML = createOutsourceTable();
    }
}

// 处理搜索
function handleOutsourceSearch() {
    const query = document.getElementById('search-input')?.value?.trim() || '';
    
    if (!query) {
        filteredData = outsourceData;
    } else {
        filteredData = outsourceData.filter(item => 
            item.sequence?.toString().includes(query) ||
            item.model?.toLowerCase().includes(query.toLowerCase()) ||
            item.name?.toLowerCase().includes(query.toLowerCase()) ||
            item.supplier?.toLowerCase().includes(query.toLowerCase()) ||
            item.location?.toLowerCase().includes(query.toLowerCase()) ||
            item.remark?.toLowerCase().includes(query.toLowerCase())
        );
    }
    
    updateOutsourceTable();
}

// 显示新增模态框
function showAddOutsourceModal() {
    const content = `
        <form id="outsource-form" class="space-y-4">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                ${createFormInput('序号', 'sequence', 'number', '', { required: true, placeholder: '请输入序号' })}
                ${createFormInput('机型', 'model', 'text', '', { required: true, placeholder: '请输入机型' })}
                ${createFormInput('名称', 'name', 'text', '', { required: true, placeholder: '请输入名称' })}
                ${createFormInput('数量', 'quantity', 'number', '', { required: true, placeholder: '请输入数量' })}
                ${createFormInput('外发厂商', 'supplier', 'text', '', { required: true, placeholder: '请输入外发厂商' })}
                ${createFormInput('外发日期', 'outsourceDate', 'date', '', { required: true })}
                ${createFormInput('预计返回日期', 'expectedReturnDate', 'date', '', { required: true })}
                ${createFormInput('实际返回日期', 'actualReturnDate', 'date', '')}
                ${createFormInput('状态', 'status', 'select', '', { 
                    required: true, 
                    options: [
                        { value: '待外发', text: '待外发' },
                        { value: '外发中', text: '外发中' },
                        { value: '已返回', text: '已返回' },
                        { value: '异常', text: '异常' }
                    ]
                })}
                ${createFormInput('位置', 'location', 'text', '', { placeholder: '请输入当前位置' })}
            </div>
            ${createFormInput('备注', 'remark', 'textarea', '', { placeholder: '请输入备注信息' })}
        </form>
    `;
    
    showModal('新增外发清单', content, () => {
        const form = document.getElementById('outsource-form');
        if (form.checkValidity()) {
            const formData = new FormData(form);
            const data = {};
            
            for (let [key, value] of formData.entries()) {
                data[key] = value;
            }
            
            createOutsource(data);
        } else {
            form.reportValidity();
        }
    });
    
    // 重新绑定表单提交事件
    setTimeout(() => {
        const modal = document.querySelector('.modal');
        const confirmBtn = modal.querySelector('.btn-primary');
        confirmBtn.onclick = () => {
            const form = document.getElementById('outsource-form');
            if (form.checkValidity()) {
                const formData = new FormData(form);
                const data = {};
                
                for (let [key, value] of formData.entries()) {
                    data[key] = value;
                }
                
                createOutsource(data);
                modal.remove();
            } else {
                form.reportValidity();
            }
        };
    }, 100);
}

// 创建外发清单
async function createOutsource(data) {
    try {
        await outsourceAPI.create(data);
        showSuccess('创建成功');
        loadOutsourceData();
    } catch (error) {
        showError('创建失败');
    }
}

// 编辑外发清单
function editOutsource(id) {
    const item = outsourceData.find(o => o.id === id);
    if (!item) {
        showError('记录不存在');
        return;
    }
    
    const content = `
        <form id="outsource-edit-form" class="space-y-4">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                ${createFormInput('序号', 'sequence', 'number', item.sequence, { required: true })}
                ${createFormInput('机型', 'model', 'text', item.model, { required: true })}
                ${createFormInput('名称', 'name', 'text', item.name, { required: true })}
                ${createFormInput('数量', 'quantity', 'number', item.quantity, { required: true })}
                ${createFormInput('外发厂商', 'supplier', 'text', item.supplier, { required: true })}
                ${createFormInput('外发日期', 'outsourceDate', 'date', item.outsourceDate, { required: true })}
                ${createFormInput('预计返回日期', 'expectedReturnDate', 'date', item.expectedReturnDate, { required: true })}
                ${createFormInput('实际返回日期', 'actualReturnDate', 'date', item.actualReturnDate || '')}
                ${createFormInput('状态', 'status', 'select', item.status, { 
                    required: true, 
                    options: [
                        { value: '待外发', text: '待外发' },
                        { value: '外发中', text: '外发中' },
                        { value: '已返回', text: '已返回' },
                        { value: '异常', text: '异常' }
                    ]
                })}
                ${createFormInput('位置', 'location', 'text', item.location || '')}
            </div>
            ${createFormInput('备注', 'remark', 'textarea', item.remark || '')}
        </form>
    `;
    
    showModal('编辑外发清单', content, () => {
        const form = document.getElementById('outsource-edit-form');
        if (form.checkValidity()) {
            const formData = new FormData(form);
            const data = {};
            
            for (let [key, value] of formData.entries()) {
                data[key] = value;
            }
            
            updateOutsource(id, data);
        } else {
            form.reportValidity();
        }
    });
    
    // 重新绑定表单提交事件
    setTimeout(() => {
        const modal = document.querySelector('.modal');
        const confirmBtn = modal.querySelector('.btn-primary');
        confirmBtn.onclick = () => {
            const form = document.getElementById('outsource-edit-form');
            if (form.checkValidity()) {
                const formData = new FormData(form);
                const data = {};
                
                for (let [key, value] of formData.entries()) {
                    data[key] = value;
                }
                
                updateOutsource(id, data);
                modal.remove();
            } else {
                form.reportValidity();
            }
        };
    }, 100);
}

// 更新外发清单
async function updateOutsource(id, data) {
    try {
        await outsourceAPI.update(id, data);
        showSuccess('更新成功');
        loadOutsourceData();
    } catch (error) {
        showError('更新失败');
    }
}

// 删除外发清单
function deleteOutsource(id) {
    showConfirmDialog('确定要删除这条记录吗？', async () => {
        try {
            await outsourceAPI.delete(id);
            showSuccess('删除成功');
            loadOutsourceData();
        } catch (error) {
            showError('删除失败');
        }
    });
}

// 导出外发数据
function exportOutsourceData() {
    if (filteredData.length === 0) {
        showWarning('没有数据可导出');
        return;
    }
    
    const exportData = filteredData.map(item => ({
        '序号': item.sequence,
        '机型': item.model,
        '名称': item.name,
        '数量': item.quantity,
        '外发厂商': item.supplier,
        '外发日期': item.outsourceDate,
        '预计返回日期': item.expectedReturnDate,
        '实际返回日期': item.actualReturnDate || '',
        '状态': item.status,
        '备注': item.remark || '',
        '位置': item.location || ''
    }));
    
    exportToCSV(exportData, `外发清单_${formatDate(new Date(), 'YYYY-MM-DD')}.csv`);
    showSuccess('导出成功');
}

// 绑定到全局作用域
window.loadOutsourcePage = loadOutsourcePage;
window.showAddOutsourceModal = showAddOutsourceModal;
window.editOutsource = editOutsource;
window.deleteOutsource = deleteOutsource;
window.exportOutsourceData = exportOutsourceData;
